package com.arcvideo.acsplayer.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.arcvideo.acsplayer.R;
import com.arcvideo.acsplayer.dialog.ProgressDialog;
import com.arcvideo.acsplayer.local.AbstructProvider;
import com.arcvideo.acsplayer.local.LoadedImage;
import com.arcvideo.acsplayer.local.VideoProvider;
import com.arcvideo.acsplayer.mode.LocalVideoInfo;
import com.arcvideo.acsplayer.utils.DateUtil;

public class LoadLocalActivity extends Activity implements OnClickListener, OnItemClickListener {
	private TextView mTitleText = null;
	private ImageButton mBackButton = null;
	private ListView mVideoListView = null;
	private int mCurrentPosition = 0;
	private ProgressDialog mLoadingDialog = null;

	private VideoListViewAdapter mVideoListViewAdapter = null;
	private ArrayList<LocalVideoInfo> mVideoList = null;
	private int videoSize = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_load_local);
		initUi();
		initData();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.id_title_left_btn :
				finish();
				break;
			default :
				break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		mCurrentPosition = position;
		toPlayActivity();
	}

	/**
	 * 初始化UI
	 */
	private void initUi() {
		mTitleText = (TextView) findViewById(R.id.id_title_text_view);
		mTitleText.setText(R.string.select_video_from_local);

		mBackButton = (ImageButton) findViewById(R.id.id_title_left_btn);
		mBackButton.setOnClickListener(this);

		mVideoListView = (ListView) findViewById(R.id.list);
		mVideoListView.setOnItemClickListener(this);

		mLoadingDialog = ProgressDialog.createDialog(this);
		mLoadingDialog.setMessage(getString(R.string.buffering));
		mLoadingDialog.hide();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		AbstructProvider provider = new VideoProvider(this);
		mVideoList = provider.getList();
		videoSize = mVideoList.size();
		mVideoListViewAdapter = new VideoListViewAdapter(this, mVideoList);
		mVideoListView.setAdapter(mVideoListViewAdapter);
		new Thread(new Runnable() {
			@Override
			public void run() {
				loadImages();
			}
		}).start();

	}

	/**
	 * 进入播放页面
	 */
	private void toPlayActivity() {
		Intent displayIntent = new Intent(LoadLocalActivity.this, PlayActivity.class);
		displayIntent.putExtra(PlayActivity.URLTYPE, PlayActivity.FROM_LOCAL);
		displayIntent.putExtra(PlayActivity.URLDATA, mVideoList);
		displayIntent.putExtra(PlayActivity.URLINDEX, mCurrentPosition);
		startActivity(displayIntent);
	}

	/**
	 * 加载图片
	 */
	private void loadImages() {
		final Object data = getLastNonConfigurationInstance();
		if (data == null) {
			new LoadImagesFromSDCard().execute();
		} else {
			final LoadedImage[] photos = (LoadedImage[]) data;
			if (photos.length == 0) {
				new LoadImagesFromSDCard().execute();
			}
			for (LoadedImage photo : photos) {
				addImage(photo);
			}
		}
	}

	/**
	 * 添加图片
	 *
	 * @param value
	 */
	private void addImage(LoadedImage... value) {
		for (LoadedImage image : value) {
			mVideoListViewAdapter.addPhoto(image);
			mVideoListViewAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 保存图片
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		final ListView grid = mVideoListView;
		final int count = grid.getChildCount();
		final LoadedImage[] list = new LoadedImage[count];

		for (int i = 0; i < count; i++) {
			final ImageView v = (ImageView) grid.getChildAt(i);
			list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
		}

		return list;
	}

	/**
	 * 获取视频缩略图
	 *
	 * @param videoPath
	 * @param width
	 * @param height
	 * @param kind
	 * @return
	 */
	private Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
		Bitmap bitmap = null;
		bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	/**
	 * 从SD卡加载图片
	 *
	 * @author skl5250
	 *
	 */
	private class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
		@Override
		protected Object doInBackground(Object... params) {
			Bitmap bitmap = null;
			for (int i = 0; i < videoSize; i++) {
				bitmap = getVideoThumbnail(mVideoList.get(i).getPath(), 120, 120, Thumbnails.MINI_KIND);
				if (bitmap != null) {
					publishProgress(new LoadedImage(bitmap));
				}
			}
			return null;
		}

		@Override
		public void onProgressUpdate(LoadedImage... value) {
			addImage(value);
		}
	}

	/**
	 * 视频列表
	 *
	 * @author skl5250
	 *
	 */
	public class VideoListViewAdapter extends BaseAdapter {

		ArrayList<LocalVideoInfo> mVideoList;
		private LayoutInflater mLayoutInflater;
		private ArrayList<LoadedImage> mthumeNails = new ArrayList<LoadedImage>();
		public VideoListViewAdapter(Context context, ArrayList<LocalVideoInfo> videoList) {

			mLayoutInflater = LayoutInflater.from(context);
			this.mVideoList = videoList;
		}

		@Override
		public int getCount() {
			return mVideoList.size();
		}

		public void addPhoto(LoadedImage image) {
			mthumeNails.add(image);
		}
		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = mLayoutInflater.inflate(R.layout.item_local, null);
				viewHolder.video_thume = (ImageView) convertView.findViewById(R.id.left_img);
				viewHolder.video_title = (TextView) convertView.findViewById(R.id.video_title);
				viewHolder.video_time = (TextView) convertView.findViewById(R.id.video_time);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			String title = mVideoList.get(position).getTitle();
			if (title.length() > 20) {
				title = title.substring(0, 20) + "...";
			}
			viewHolder.video_title.setText(title);// ms
			viewHolder.video_time.setText(DateUtil.getTimeCount(mVideoList.get(position).getDuration()));
			if (position < mthumeNails.size()) {
				viewHolder.video_thume.setImageBitmap(mthumeNails.get(position).getBitmap());
			}
			return convertView;
		}

		private class ViewHolder {
			public ImageView video_thume;
			public TextView video_title;
			public TextView video_time;
		}
	}
}